package com.sense.kukoo.common.repo.kv.search

import com.sense.kukoo.common.repo.bean.SearchHistoryBean
import com.sense.kukoo.common.repo.kv.KukooKeyValueManager
import com.tencent.mmkv.MMKV

class SearchHistoryImpl(val mmkv: MMKV):SearchHistory {

    override fun getSearchHistory(): List<String> {
        val history = mmkv.decodeParcelable(KukooKeyValueManager.KEY_HISTORY, SearchHistoryBean::class.java)
            ?: SearchHistoryBean(arrayListOf())

        return history.mData
    }

    override fun addNewSearch(text: String) {
        val history = mmkv.decodeParcelable(KukooKeyValueManager.KEY_HISTORY, SearchHistoryBean::class.java)
            ?: SearchHistoryBean(arrayListOf())

        val remove:Boolean = history.mData.remove(text)
        history.mData.add(0, text)
        if(history.mData.size >= 16){
            history.mData.removeAt(15)
        }
        //
        mmkv.encode(KukooKeyValueManager.KEY_HISTORY, history)
    }

    override fun deleteSearch(text: String) {
        val history = mmkv.decodeParcelable(KukooKeyValueManager.KEY_HISTORY, SearchHistoryBean::class.java)
            ?: SearchHistoryBean(arrayListOf())

        val remove:Boolean = history.mData.remove(text)
        //
        mmkv.encode(KukooKeyValueManager.KEY_HISTORY, history)
    }

    override fun deleteAllSearch() {
        val history = mmkv.decodeParcelable(KukooKeyValueManager.KEY_HISTORY, SearchHistoryBean::class.java)
            ?: SearchHistoryBean(arrayListOf())
        history.mData.clear()
        //
        mmkv.encode(KukooKeyValueManager.KEY_HISTORY, history)
    }
}